package alternate;

/**
 * @author wcj
 * @Date 2021/7/22 11:58
 * @Version 1.0
 */
public class VolatileImpl {

    private static volatile boolean isOdd = true;
    private static volatile boolean isEven = true;
    private static volatile int count = 1;

    public static void main(String[] args) {

        // 偶数线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    boolean interrupted = Thread.currentThread().isInterrupted();
                    if (interrupted) {
                        break;
                    }
                    // 不满足条件自旋等待，类似于轮换法
                    while (isEven) {

                    }
                    if (count > 100) {
                        break;
                    }

                    System.out.println(Thread.currentThread().getName() + ":" + count++);

                    isOdd = false;
                    isEven = true;
                }
            }
        }, "偶数线程").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    boolean interrupted = Thread.currentThread().isInterrupted();
                    if (interrupted) {
                        break;
                    }
                    while (isOdd) {

                    }
                    if (count > 100) {
                        break;
                    }
                    System.out.println(Thread.currentThread().getName() + ":" + count++);

                    isEven = false;
                    isOdd = true;
                }
            }
        }, "奇数线程").start();

        isOdd = false;
    }
}
